;
(function () {
  'use strict';
  angular.module('services.analysisSysOM.responseTime')
    .service('historicalTimeService', historicalTimeService);

  function historicalTimeService($http, $filter, CoreService,$timeout) {
    var time = new Date();
    var date = new Date(time.getFullYear(), time.getMonth(), time.getDate() - 1); //页面时间默认当前日期的前一天
    //var date = new Date();
    //页面参数
    this.param = {
      businessLineCode: 0,
      businessLineName: '',
      tradTypeCode: 1,
      tradTypeName: '',
      date: date
    };
    this.paramc={};
    this.dataList = [];//返回数据列表
    this.viewType = 'chart';//视图类型(饼图、折线图)
    this.showSearchPanel = true;//显示查询面板
    this.showIcon = true;   //显示折线 表格图标选项
    this.busLineList = [];//业务线列表
    this.businessLineList = [];//业务线列表
    this.tradTypeList = [];//交易类型列表
    this.showArrow = true;  //控制查询面板箭头的显示和隐藏 
    var that = this;
    var chart = null;

    //隐藏查询面板
    this.hideSearchPanel = function () {
      this.showSearchPanel = false;
    };

    this.reset = function () {
      that.showSearchPanel = true;
      that.viewType = 'chart';
      that.param.date = date;
      that.busLineList = [];
      that.dataList = [];
    };

    //初始化页面下拉列表选项
    this.initSelectMenu = function () {
      //获取业务线
      $http.get('/sas/common/businessLineQuery')
        .then(function (res) {
          if (res.data.state === '10000') {
            that.businessLineList = res.data.data;
            that.param.businessLineCode = res.data.data[0].businessLineCode;
            //获取交易类型
            $http.post('/sas/analysisSysOM/sysPerformance/tradType/query', {businessCode: res.data.data[0].businessLineCode})
              .then(function (resType) {
                if (resType.data.state === '10000') {
                  that.tradTypeList = resType.data.data;
                  that.param.tradTypeCode = resType.data.data[0].tradCode;
                  that.search();
                }
              }, function (resType) {
              }
            );
          }

        }, function (res) {
        }
      );
      //that.search();
    };
    //根据业务线 联动 交易类型
    this.getTradType = function () {
      //获取交易类型
      $http.post('/sas/analysisSysOM/sysPerformance/tradType/query', {businessCode: that.param.businessLineCode})
        .then(function (resType) {
          if (resType.data.state === '10000' && resType.data) {
            that.tradTypeList = resType.data.data;
            that.param.tradTypeCode = resType.data.data[0].tradCode;
          }
        }, function (resType) {
        }
      );
    };

    //查询历史响应时间
    this.search = function () {
      
      //根据Code获取Name 传参
      var businessLine = that.businessLineList.filter(function (obj) {
        if (that.param.businessLineCode === obj.businessLineCode) {
          return obj;
        }
      })[0];
      that.param.businessLineName = businessLine.businessLineName;

      var tradType = that.tradTypeList.filter(function (obj) {
        if (that.param.tradTypeCode === obj.tradCode) {
          return obj;
        }
      })[0];
      that.param.tradTypeName = tradType.tradName;

      //查询面板的显示隐藏设置
      if (!that.showSearchPanel) {
        that.showSearchPanel = true;
        return;
      }
      //copy时间 参数date的格式转换
      that.paramc = angular.copy(that.param);
      that.paramc.date = $filter('date')(that.paramc.date, 'yyyy-MM-dd');
      $http.post('/sas/analysisSysOM/sysPerformance/responsetime/showHistoricalData/query', that.paramc)
        .then(function (res) {
          that.showSearchPanel = false;
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            that.dataList = res.data.data;
            that.showArrow = true;
            that.changeViewType();   //视图显示类型  无参数即默认折线图
            that.showIcon = true;
          } else if (res.data.data.length === 0) {
            that.showArrow = false;
            that.showSearchPanel = true;
            that.showIcon = false;  //隐藏表格和折线图标
            that.dataList = [];
            chart && chart.clear();
            CoreService.dialog('查询无数据');
          } else {
            that.showArrow = false;
            that.showIcon = false;  //隐藏表格和折线图标
            that.showSearchPanel = true;
            that.dataList = [];
            chart && chart.clear();
            CoreService.dialog('查询错误');
          }
        }, function (res) {
        }
      );
    };
    //切换视图
    this.changeViewType = function (type) {
      initChart();
      that.onSubmit();
      var ta = document.getElementById('ta');
      var cha = document.getElementById('cha');
      that.viewType = type || that.viewType;
      if (that.viewType === 'chart') {
        ta.style.backgroundColor = "";
        cha.style.backgroundColor = "#2196F3";
        setTimeout(initChart, 0);
      } else if (that.viewType === 'table') {
        ta.style.backgroundColor = "#2196F3";
        cha.style.backgroundColor = "";
        initTable();
      }
    };

    //初始化图表(折线)
    function initChart() {
      chart = echarts.init(document.getElementById('historicalTimeChart'));  //初始化页面 对应模块Id 以图表填充
      var option = {
        animation:false,
        title: {
          text: $filter('date')(that.paramc.date, 'yyyy年MM月dd日') + that.paramc.businessLineName + that.paramc.tradTypeName + '响应时间',
          x: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            var str = params[0].name;
            angular.forEach(params, function (param) {
              str += '<br/>' + param.seriesName + ': ' + param.value + ' ms';
            });
            return str;
          }
        },
        legend: {data: ['最高响应时间', '最低响应时间', '平均响应时间'], x: 'right', y: 'center', orient: 'vertical'},
        xAxis: [{type: 'category', boundaryGap: false, data: [], splitLine: {show: false}}],
        yAxis: [
          {
            name: '响应时间（ms）',
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {name: '最高响应时间', type: 'line', data: []},
          {name: '最低响应时间', type: 'line', data: []},
          {name: '平均响应时间', type: 'line', data: []}
        ],
        grid: {x: '104', x2: '120'}
      };
      angular.forEach(that.dataList, function (obj) {
        option.xAxis[0].data.push(obj.timeLine);   //横轴时间刻度
        option.series[0].data.push(obj.maxTime);
        option.series[1].data.push(obj.minTime);
        option.series[2].data.push(obj.avgTime);
      });
      chart.setOption(option);
      /*$timeout(function(){
        that.onSubmit();
      },500);*/
    }

    //初始化表格业务线列表
    function initTable() {
      that.title = $filter('date')(that.paramc.date, 'yyyy年MM月dd日') + that.paramc.businessLineName + that.paramc.tradTypeName + '响应时间';
      that.busLineList = [];

      for (var key in that.dataList[0]) {
        //过滤'$$'
        if (key.indexOf('$$') === -1) {
          that.busLineList.push(key.toUpperCase());
        }
      }
    }


    //导出excel
    this.sendData = {date: ''};
    this.onSubmit = function () {
      var data = {
        date: $filter('date')(that.paramc.date, 'yyyy-MM-dd'),
        base64s: [chart.getDataURL('png').split(',')[1]],
        title: $filter('date')(that.paramc.date, 'yyyy年MM月dd日') + that.paramc.businessLineName + that.paramc.tradTypeName + '响应时间',
        businessLineCode: that.paramc.businessLineCode,
        businessLineName: that.paramc.businessLineName,
        tradTypeCode: that.paramc.tradTypeCode,
        tradTypeName: that.paramc.tradTypeName
      };
      
      that.sendData = JSON.stringify(data);

    };
  }

  historicalTimeService.$inject = ['$http', '$filter', 'CoreService','$timeout'];
})();